<template>
  <div class="padding-tb">
    <el-card class="margin-bottom">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">总计</span>
        <span>
          &nbsp;&nbsp;&nbsp;投保金额：{{
            Constatvariable["serviceInsuranceFee"]
          }}</span
        >
      </div>
      <el-row :gutter="30" type="flex">
        <el-col
          :span="4"
          v-if="
            verifyShow.superAdmin ||
              (!verifyShow.shippingOperte && !verifyShow.saler)
          "
        >
          <el-row class="row-item">
            <el-col :span="12">
              应收：
            </el-col>
            <el-col :span="12">
              {{ receiveTotalCost }} {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              应付：
            </el-col>
            <el-col :span="12">
              {{ payTotalCost }} {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              利润：
            </el-col>
            <el-col :span="12">
              {{
                (Number(receiveTotalCost) * 1000 -
                  Number(payTotalCost) * 1000) /
                  1000
              }}
              {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              利润率：
            </el-col>
            <el-col :span="12">
              {{ profit }}
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="5" class="border-lr">
          <el-row class="row-item">
            <el-col :span="12">
              应收公司合计：
            </el-col>
          </el-row>
          <el-row class="row-item" v-for="(item, k) in receiveMap" :key="k">
            <el-col :span="12">
              {{ k }}：
              <span v-for="(m, n) in item" :key="m" :value="n">
                {{ m }} {{ n }}
              </span>
            </el-col>
          </el-row>
        </el-col>
        <el-col
          :span="15"
          v-if="
            verifyShow.superAdmin ||
              (!verifyShow.shippingOperte && !verifyShow.saler)
          "
        >
          <el-row class="row-item">
            <el-col :span="3">
              应付公司合计：
            </el-col>
          </el-row>
          <el-row class="row-item" v-for="(item, k) in payMap" :key="k">
            <el-col :span="12">
              {{ k }}：
              <span v-for="(m, n) in item" :key="m" :value="n">
                {{ m }} {{ n }}
              </span>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="margin-bottom" v-if="verifyShow.receView">
      <div slot="header" class="clearfix relative">
        <span class="title-icon"
          >应收
          <span v-if="waybillReceiveType">
            <span
              style="color:#409eff"
              v-for="(m, n) in collectMap"
              :key="m"
              :value="n"
            >
              {{ n }}: {{ m }}
            </span>
            快递总毛重: {{ totalexpressweight }}
          </span>
        </span>
        <!-- <el-button
          v-if="loadingOver && verifyShow.editRece"
          type="success"
          size="mini"
          class="header-save-btn"
          v-loading.fullscreen.lock="fullscreenLoading"
          @click="changeReceivable"
        >
          {{ isChangeReceivable ? "编辑中" : "编辑" }}
        </el-button> -->
        <el-button
          size="mini"
          type="text"
          style="margin-left: 50px;"
          @click="repairAllReceiveSynToAmoeba"
        >
          <el-tooltip
            effect="light"
            placement="bottom"
            content="应收(未结转)重新同步到阿米巴"
          >
            <i class="el-icon-refresh" style="font-size:20px"></i>
          </el-tooltip>
        </el-button>
        <el-button
          style="margin-right:85px;"
          v-if="Constatvariable['status'] != 999 && verifyShow.createRece"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="addReceivable"
        >
          新增
        </el-button>
        <el-button
          style="margin-right:125px;"
          v-if="Constatvariable['status'] != 999"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="copyReceivableinfo"
        >
          <el-tooltip effect="light" placement="bottom" content="复制应收">
            <i class="el-icon-document-copy" style="font-size:20px"></i>
          </el-tooltip>
        </el-button>

        <el-button
          style="margin-right:255px;"
          v-if="
            Constatvariable['hdType'] &&
              Constatvariable['referenceNo'] != '' &&
              Constatvariable['customerId'] != ''
          "
          type="text"
          size="mini"
          class="header-save-btn"
          @click="pushReceiveToCustomer"
        >
          推送数据到{{
            initOptionsData["customerMap"][Constatvariable.customerId]
          }}
        </el-button>
      </div>

      <HotTable
        ref="receivableHotTable"
        :templateName="`Receivable`"
        :templateData.sync="receivableData"
        :oldData="receivableData"
        :templateOptUser="optUser"
        :receveToPay.sync="payableData"
        :verifyShow.sync="verifyShow"
        :templateOptions="templateOptions"
        :templateType="`receivable`"
        :Constatvariable="Constatvariable"
        :initOptionsData="initOptionsData"
        :templateDelReceveIds="delReceveIds"
        @getinfo="lazyloadWaybillReceivePayables"
        class="margin-top text-sm"
      ></HotTable>
    </el-card>
    <div v-if="verifyShow.payView" class="padding-tb-sm">
      <el-row>
        <el-col :span="6">
          <span style="margin-left:20px;" class="title-icon"
            >服务商账单导入：请先选择服务商</span
          >
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="parseServicerId"
            @change="chnageUpload"
            placeholder="请选择类型"
            filterable
            clearable
            size="mini"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(k, v) in parseServicerMap"
              :key="k"
              :label="parseServicerMap[v]"
              :value="parseInt(v)"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>
    <el-card v-if="uploadShow">
      <el-upload
        class="upload-demo"
        ref="upload"
        drag
        action="fakeaction"
        :show-file-list="true"
        :http-request="uploadFn"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
      <el-button
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click="submitUpload"
        v-loading.fullscreen.lock="fullscreenLoading"
        >上传到服务器</el-button
      >
    </el-card>
    <el-card v-if="verifyShow.superAdmin || verifyShow.payView">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">应付</span>
        <el-button
          size="mini"
          type="text"
          style="margin-left: 50px;"
          @click="repairAllPaySynToAmoeba"
        >
          <el-tooltip
            effect="light"
            placement="bottom"
            content="应付(未结转)重新同步到阿米巴"
          >
            <i class="el-icon-refresh" style="font-size:20px"></i>
          </el-tooltip>
        </el-button>
        <el-button
          style="margin-right:85px;"
          v-if="verifyShow.createPay"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="addPayable"
        >
          新增
        </el-button>
        <el-button
          style="margin-right:125px;"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="copyPaymentinfo"
        >
          <el-tooltip effect="light" placement="bottom" content="复制应付">
            <i class="el-icon-document-copy" style="font-size:20px"></i>
          </el-tooltip>
        </el-button>
      </div>

      <HotTable
        ref="payableHotTable"
        :templateName="`Receivable`"
        :templateData.sync="payableData"
        :oldData="payableData"
        :verifyShow.sync="verifyShow"
        :templateOptUser="optUser"
        :payToReceve.sync="receivableData"
        :templateOptions="templateOptions"
        :templateType="`payable`"
        :templateDelPayIds="delPayIds"
        @getinfo="lazyloadWaybillReceivePayables"
        class="margin-top text-sm"
      ></HotTable>
    </el-card>
    <CopyReceivable
      ref="CopyReceivable"
      :receivableData.sync="receivableData"
    ></CopyReceivable>
    <CopyPayment
      ref="CopyPayment"
      :payableData.sync="payableData"
      :templateType="`payable`"
    ></CopyPayment>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { untransform } from "@/store/yg/common/uri";
import { clone } from "@/utils/clone";
import { parseTime } from "@/utils";
import HotTable from "./HotTable";
import CopyReceivable from "./CopyReceivable";
import CopyPayment from "./CopyPayment";
import { m } from "@/store/yg/common/local";

export default {
  components: {
    HotTable,
    CopyReceivable,
    CopyPayment
  },
  props: {
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    initOptionsData: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      waybillReceiveType: false,
      //快递总毛重
      totalexpressweight: "",
      collectMap: {},
      receiveIds: 0,
      payIds: 0,
      fullscreenLoading: false,
      templateOptions: {
        //C类
        paycOptions: ["C0", "C1", "C2", "C3"],
        //账单类型
        options: ["起", "目"],
        //币种
        currencyOptions: [],
        //费用名称：
        configPayNameOptions: [],
        //费用类型
        configPayTypeOptions: [],
        //用户信息
        userOptions: [],
        // 应收对应客户
        companyOptions: [],
        // 应付对应服务商
        serviceOptions: [],
        payNameTypeMap: {}
      },
      loadingOver: false,
      //当前用户
      optUser: "",
      //记录应收删除的ID
      delReceveIds: [],
      //记录应付删除的ID
      delPayIds: [],
      //应收
      receiveTotalCost: 0,
      //应付
      payTotalCost: 0,
      //利润率
      profit: "0%",
      //应付信息
      payMap: {},
      //应收信息
      receiveMap: {},
      standardCurrency: "RMB",
      restaurants: [],
      selectionList: [],
      selectionPayableList: [],
      isChangeReceivable: false,
      isChangePayable: false,
      //服务商解析管理
      parseServicerMap: {},
      tabColumns: [
        { prop: "serCusId", label: "公司" },
        { prop: "costName", label: "费用名称" },
        { prop: "costNameType", label: "类型" },
        { prop: "configPayTypec", label: "C类" },
        { prop: "responsibleId", label: "责任人" },
        { prop: "count", label: "数量" },
        { prop: "unitPrice", label: "单价" },
        { prop: "currency", label: "币种" },
        { prop: "totalCost", label: "总额" },
        { prop: "remain", label: "余额" },
        { prop: "billType", label: "账单类型" },
        { prop: "inputUser", label: "录入人" },
        { prop: "lastOperator", label: "修改人" },
        { prop: "remark", label: "备注" },
        { prop: "accountDate", label: "费用日期" },
        { prop: "billingDate", label: "销账日期" },
        { prop: "cdate", label: "创建日期" }
      ],
      tabColumns2: [
        { prop: "serCusId", label: "公司" },
        { prop: "costName", label: "费用名称" },
        { prop: "costNameType", label: "类型" },
        { prop: "configPayTypec", label: "C类" },
        { prop: "responsibleId", label: "责任人" },
        { prop: "count", label: "数量" },
        { prop: "unitPrice", label: "单价" },
        { prop: "currency", label: "币种" },
        { prop: "totalCost", label: "总额" },
        { prop: "remain", label: "余额" },
        { prop: "billType", label: "账单类型" },
        { prop: "isAllocated", label: "是否分配" },
        { prop: "inputUser", label: "录入人" },
        { prop: "lastOperator", label: "修改人" },
        { prop: "remark", label: "备注" },
        { prop: "accountDate", label: "费用日期" },
        { prop: "billingDate", label: "销账日期" },
        { prop: "cdate", label: "创建日期" }
      ],
      receivableData: [],
      payableData: [],
      action: "",
      feeData: [],
      fileList: [{ name: "", url: "" }],
      uploadShow: false,
      parseServicerId: "",
      oldData: {
        receivableData: [],
        payableData: []
      }
    };
  },
  watch: {
    verifyShow: {
      handler(val) {
        console.log("waybill verifyShow :>> ", val);
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    repairAllPaySynToAmoeba() {
      var param = {};
      const waybillId = this.$route.query.waybillId;
      param["id"] = waybillId;
      ajax("repairAllPaySynToAmoeba", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("更新失败!");
            }
          } else {
            this.$message.success("更新成功!");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    repairAllReceiveSynToAmoeba() {
      var param = {};
      const waybillId = this.$route.query.waybillId;
      param["id"] = waybillId;
      ajax("repairAllReceiveSynToAmoeba", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("更新失败!");
            }
          } else {
            this.$message.success("更新成功!");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    pushReceiveToCustomer() {
      var param = {};
      ajax("pushReceiveToCustomer", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("推送失败!");
            }
          } else {
            this.$message.success("推送成功!");
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    copyPaymentinfo() {
      this.$refs.CopyPayment.centerDialogVisible = true;
    },
    copyReceivableinfo() {
      this.$refs.CopyReceivable.centerDialogVisible = true;
    },
    chnageUpload() {
      this.uploadShow = true;
    },
    uploadFn(params) {
      //自定义上传文件

      const file = params.file,
        fileType = file.type,
        isImage = fileType.indexOf("pdf") !== -1,
        isLt4M = file.size / 1024 / 1024 < 4;
      // 这里常规检验，看项目需求而定
      // if (!isImage) {
      //  this.$message.error("只能上传pdf格式!");
      //  return;
      // }

      //if (!isLt4M) {
      //   this.$message.error("只能上传图片大小小于4M");
      //   return;
      //  }
      // 根据后台需求数据格式
      if (this.parseServicerId === null || "" === this.parseServicerId) {
        this.$message.error("请选择服务商");
        return;
      }

      const form = new FormData();
      // 文件对象

      form.append("items[]", file);
      form.append("servicerParseId", this.parseServicerId);
      form.append("waybillId", this.$route.query.waybillId);
      this.fullscreenLoading = true;
      axios({
        method: "post",
        url: this.action,
        data: form
      })
        .then(response => {
          this.fullscreenLoading = false;
          if (response.data.code === 200) {
            // this.feeData.push({
            //   mes: response.data.data.fileName,
            //   fee: response.data.data.fullFileName
            // });
            this.$message.success("导入成功");
            this.fullscreenLoading = true;
            this.lazyloadWaybillReceivePayables();
          } else {
            this.$notify.error({
              title: "错误",
              message: "上传失败!" + response.data.message
            });
          }
        })
        .catch(error => {
          console.log(error);
          this.$notify.error({
            title: "错误",
            message: "上传失败!"
          });
        });
    },

    handleSelectionChange(val) {
      console.log(
        "%cval: ",
        "color: MidnightBlue; background: Aquamarine;",
        val
      );
      this.selectionList = val;
    },
    addReceivable() {
      console.log("this.templateOptions :>> ", this.templateOptions);
      const data = clone(this.receivableData);
      console.log("data :>> ", data);
      this.receiveIds++;
      console.log("应收唯一id", this.receiveIds);
      var receive = {
        id: "",
        onlyKey: this.receiveIds,
        serCusId: this.initOptionsData["customerMap"][
          this.Constatvariable.customerId
        ],
        costName: "",
        costNameType: "",
        configPayTypec: "",
        responsibleId: "",
        inputUser: this.optUser,
        lastOperator: "",
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      console.log("this.receivableData :>> ", this.receivableData);
      this.receivableData = [...data, ...[receive]];

      this.oldData.receivableData = clone(this.receivableData);
    },
    addPayable() {
      this.payIds++;
      var payble = {
        id: "",
        onlyKey: this.payIds,
        serCusId: "",
        costName: "",
        costNameType: "",
        configPayTypec: "",
        responsibleId: "",
        inputUser: this.optUser,
        lastOperator: "",
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      this.payableData.push(payble);

      this.oldData.payableData = clone(this.payableData);
    },
    payableSelectionChange(val) {
      this.selectionPayableList = val;
    },
    changeReceivable() {
      if (this.isChangeReceivable) {
        this.isChangeReceivable = false;
      } else {
        this.isChangeReceivable = true;
      }
    },
    changePayable() {
      if (this.isChangePayable) {
        this.isChangePayable = false;
      } else {
        this.isChangePayable = true;
      }
    },

    addselect(type) {
      if (type === "receivable") {
        this.receivableData = this.addSelectRow(this.receivableData);
      } else {
        this.payableData = this.addSelectRow(this.payableData);
      }
    },
    addSelectRow(arrList) {
      let obj = {
        serCusId: "",
        costName: "",
        costNameType: "",
        configPayTypec: "",
        responsibleId: "",
        inputUser: "",
        lastOperator: "",
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      console.log("obj", obj);
      arrList.push(obj);
      return arrList;
    },

    copyToPayable(data) {
      console.log("this.$children :>> ", this.$children);
      this.$confirm("确认复制到应付？")
        .then(_ => {
          const target = clone(data.row);
          if (this.checkRule(target)) {
            target.accountDate = target.cdate = parseTime(
              new Date().toLocaleDateString(),
              "{y}-{m}-{d}"
            );
            // TODO 公司名=运单对应清关服务商 || ''
            this.payableData.push(target);
            // TODO 保存操作 更新数据
            console.log("this.$children :>> ", this.$children);
          }
        })
        .catch(_ => {});
    },
    copyToReceivable(data) {
      this.$confirm("确认复制到应收？")
        .then(_ => {
          const target = clone(data.row);
          if (this.checkRule(target)) {
            target.accountDate = target.cdate = parseTime(
              new Date().toLocaleDateString(),
              "{y}-{m}-{d}"
            );
            // TODO 公司名等于当前客户
            this.receivableData.push(target);
            // TODO 保存操作 更新数据
          }
        })
        .catch(_ => {});
    },
    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error("请填写公司名");
        return false;
      } else if (!i.costName) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (i.costNameType === "C" && !i.configPayTypec) {
        this.$message.error("请选择C类");
        return false;
      } else if (i.configPayTypec === "C3" && !i.responsibleId) {
        this.$message.error("请填写责任人");
        return false;
      } else if (!i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (!i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      } else if (!i.billType) {
        this.$message.error("请填写账单类型");
        return false;
      }

      return true;
    },

    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    lazyloadWaybillReceivePayables() {
      var param = {};
      //直接从缓存获取
      const waybillId = this.$route.query.waybillId;
      param["id"] = waybillId;
      ajax("lazyloadWaybillReceivePayables", param)
        .then(res => {
          this.fullscreenLoading = false;
          console.log("加载应收应付数据", res);
          if (res.code == 200) {
            this.templateOptions.currencyOptions = res.data["currencyMap"];
            this.templateOptions.configPayNameOptions =
              res.data["configPayNameMap"];
            this.templateOptions.configPayTypeOptions =
              res.data["configPayTypeMap"];
            this.templateOptions.userOptions = res.data["userMap"];
            this.templateOptions.companyOptions = res.data["customerMap"];
            this.templateOptions.serviceOptions = res.data["serviceCompanyMap"];
            this.templateOptions.payNameTypeMap = res.data["payNameTypeMap"];
            this.receivableData = res.data["receives"];
            this.payableData = res.data["pays"];
            this.receiveTotalCost = res.data["receiveTotalCost"];
            this.payTotalCost = res.data["payTotalCost"];
            this.profit = res.data["profit"];
            this.payMap = res.data["payMap"];
            this.parseServicerMap = res.data["parseServicerMap"];
            this.receiveMap = res.data["receiveMap"];
            this.optUser = res.data["optUser"];
            this.collectMap = res.data["collectMap"]; //末端显示用
            this.totalexpressweight = res.data["totalexpressweight"];
            this.oldData.payableData = clone(this.payableData);
            this.oldData.receivableData = clone(this.receivableData);
            //加载完才显示操作按钮
            this.loadingOver = true;
          } else {
            this.$message("数据加载失败！");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 获取销账日期
    async getBillingDate(scope, type) {
      // 存在数据
      if (scope.row.billingDate) {
        return;
      }

      // 请求数据
      // TODO
      const data = await ajax("", {});

      if (data.code !== 200) return;

      this.$set(scope.row, "billingDate", data);
    }
  },
  created: function() {
    this.action =
      constant.API_SERVER +
      "/api/consume/upload?uri=" +
      untransform(this.$route.params.uri) +
      "&f=imporWaybillPayFeePdf&type=blank&name=sub";
  },
  mounted() {
    this.lazyloadWaybillReceivePayables();
    var head =
      document.head ||
      document.getElementsByTagName("head")[0] ||
      document.documentElement;
    var baseUrl = head.baseURI;
    if (
      null != baseUrl &&
      baseUrl != "" &&
      (baseUrl.indexOf("waybill__seafreightHD__main") != -1 ||
        baseUrl.indexOf("waybill__airfreightHD__main") != -1)
    ) {
      this.waybillReceiveType = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.border-lr {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
/deep/ .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
<style>
.handsontable th {
  background: #fff;
  color: #2c3e50;
  text-align: left;
  font-weight: bold;
}

.el-card__body {
  color: #606266;
}
.handsontable th:first-child,
.handsontable th:nth-child(2),
.handsontable td:first-of-type,
.handsontable tr th,
.handsontable tr td,
.handsontable tr:first-child th,
.handsontable tr:first-child td {
  border-color: #ebeef5;
}
</style>
